<template>
  <!-- 添加或修改付款申请单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-row :gutter="24">
      <el-col :span="8">
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker clearable
                                  v-model="form.applyTime"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  placeholder="请选择申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票编号" prop="invoiceCode">
                  <el-input v-model="form.invoiceCode" placeholder="请输入发票编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="发票照片" prop="invoicePhoto">
                  <file-upload v-model="form.invoicePhoto"></file-upload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请金额:" prop="totalMoney">
                  <el-input-number v-model="form.totalMoney" :precision="2" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
                   label-width="90px">
            <el-form-item label="供应商名称" prop="supplierId">
              <el-select v-model="queryParams.supplierId" style="width: 260px;" placeholder="请选择供应商"
                         @change="handleQuery"
                         @keyup.enter.native="handleQuery" filterable clearable>
                <el-option v-for="dict in dict.type.goods_supplier"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="采购编号" prop="nos">
              <el-input v-model="queryParams.nos" placeholder="请输入采购编号" style="width: 260px;"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
                    :max-height="tableMaxHeight">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="采购编号" align="center" prop="nos" show-overflow-tooltip/>
            <el-table-column label="供应商名称" align="center" prop="supplierName" show-overflow-tooltip/>
            <el-table-column label="订单日期" align="center" prop="ddDate" width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.ddDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单金额" align="center" prop="money"/>
            <el-table-column label="定金" align="center" prop="dingjin"/>
            <el-table-column label="剩余申请" align="center" prop="payApplyRemainMoney"/>
            <el-table-column label="本次付款" align="center" prop="applyMoneyTemp" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.applyMoneyTemp" @change="sumTotalMoney()" size="mini"
                                 :max="scope.row.payApplyRemainMoney"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="采购类型" prop="goodsType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.goods_type" :value="scope.row.goodsType"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="到货状态" prop="arrivalStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.daohuo_status" :value="scope.row.arrivalStatus"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="付款状态" prop="payApplyState">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.buy_pay_status" :value="scope.row.payApplyState"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-document"
                           @click="caigou(scope.row)" v-hasPermi="['develop:LvBuy:edit']">采购明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"/>
        </el-card>
      </el-col>
    </el-row>


    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <caigou-detail-list ref="caigouDetailList" @ok="getList"></caigou-detail-list>
  </el-dialog>
</template>
<script>
import {addAction, getAction, accAdd, getById, updateAction} from '@/api/manage';
import moment from 'moment';
import {parseTime} from "@/utils/common";
import CaigouDetaiList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";
import CaigouDetailList from "@/views/develop/lvBuy/module/CaigouDetailList.vue";

export default {
  name: "PayApplyMergeListForm",
  dicts: ["goods_type", "pay_material_status", "daohuo_status", "buy_pay_status", "goods_supplier"],
  components: {CaigouDetailList, CaigouDetaiList},
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      dataList: [],
      selectRows: [],
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        cgallid: null,
        pageNum: 1,
        pageSize: 20,
        mainId: null,
        customerName: null,
        supplierName: null,
        params: {},
        orderByColumn: "a.create_time",
        isAsc: "desc",
      },
      buy: {},
      // 表单校验
      rules: {
        applyTime: [
          {required: true, message: "请选择申请时间", trigger: "blur"}
        ],
        totalMoney: [
          {required: true, message: "请输入申请付款金额", trigger: "blur"},
          {
            validator: this.totalMoneyValidator,
            trigger: 'blur'
          }
        ],
        // invoiceCode: [
        //   {required: true, message: "请输入发票编号", trigger: "blur"}
        // ],
        // invoicePhoto: [
        //   {required: true, message: "请上传发票照片", trigger: "blur"}
        // ],
      },
      url: {
        list: '/lvBuy/lvBuy/listToMerge',
        addForBuyList: '/payApply/payApply/addForBuyList',
      },
      CS: {
        'text-align': 'center',  //文本居中
        'min-width': '250px',   //最小宽度
        'word-break': 'break-all'  //过长时自动换行
      },
      LS: {
        'color': '#000',
        'text-align': 'center',
        'font-weight': '600',
        'height': '40px',
        'min-width': '110px',
        'word-break': 'keep-all'
      },
      tableMaxHeight: window.innerHeight - 350,
    };
  },
  created() {

  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.selectRows = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        buyId: null,
        applyTime: null,
        invoiceCode: null,
        invoicePhoto: null,
        totalMoney: null,
        paidMoney: null,
        remainMoney: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    totalMoneyValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('申请金额不能为0'));
      } else {
        callback();
      }
    },

    handleDaohuoCgd(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.piliangdaohuo, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("批量到货成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      const ids = this.ids;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (ids == null || ids == '' || ids == 'undefined') {
            this.$modal.msgError("请选择一条记录");
            return;
          }
          if (!this.selectRows.every(obj => obj.supplierId === this.selectRows[0].supplierId)) {
            this.$modal.msgError("多供应商信息不一致，不能一起申请付款，请检查！");
            return;
          }
          // selectRows 的 payApplyTemp 金额都不能为0
          for (let i = 0; i < this.selectRows.length; i++) {
            if (this.selectRows[i].payApplyTemp == 0) {
              this.$modal.msgError("申请金额不能为0");
              return;
            }
          }
          // 金额不能为0
          if (this.form.totalMoney == 0) {
            this.$modal.msgError("申请金额不能为0");
            return;
          }

          this.form.buyId = ids.join();
          this.form.lvBuyList = this.selectRows;
          addAction(this.url.addForBuyList, this.form).then(response => {
            this.$modal.msgSuccess("付款单申请成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },

    show() {
      this.reset();
      this.open = true;
      this.form.applyTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.queryParams.isDeposit = "N";
      this.queryParams.payApplyState = "0";
      // this.queryParams.arrivalStatus = "2";
      this.title = "付款申请单";
      this.getList();
    },

    /** 查询销售信息管理列表 */
    getList() {
      let that = this;
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        that.dataList = response.rows;
        for (let i = 0; i < that.dataList.length; i++) {
          that.dataList[i].applyMoneyTemp = that.dataList[i].payApplyRemainMoney;
        }
        that.total = response.total;
        that.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    caigou(row) {
      this.$refs.caigouDetailList.showcaigou(row);
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length;
      this.selectRows = selection;
      this.sumTotalMoney();
    },

    sumTotalMoney() {
      let totalMoney = 0;
      for (let i = 0; i < this.ids.length; i++) {
        for (let j = 0; j < this.dataList.length; j++) {
          if (this.ids[i] == this.dataList[j].id) {
            // 如果是有定金的 则申请金额为定金
            // 如果是有定金的 并且定金已付的 则申请金额为剩余金额
            totalMoney = accAdd(totalMoney, this.dataList[j].applyMoneyTemp)
          }
        }
      }
      this.form.totalMoney = totalMoney;
    },
  }
};
</script>

